package com.hyh.service.impl;

import com.hyh.bean.Role;
import com.hyh.dao.MiddleDao;
import com.hyh.dao.RoleDao;
import com.hyh.dao.impl.MiddleDaoImpl;
import com.hyh.dao.impl.RoleDaoImpl;
import com.hyh.service.RoleService;

import java.util.List;

public class RoleServiceImpl implements RoleService {

    private RoleDao roleDao = new RoleDaoImpl();
    private MiddleDao middleDao = new MiddleDaoImpl();

    @Override
    public List<Role> getRoles(int pageIndex,int pageSize) {
        return roleDao.getRoles(pageIndex, pageSize);
    }

    @Override
    public int total() {
        return roleDao.total();
    }

    @Override
    public int insertRole(String roleName, String state, String[] ids) {
        int i = 0;
        try {
            //1.新增角色表
            Role role = new Role();
            role.setRoleName(roleName);
            role.setRoleState(Integer.parseInt(state));
            int k = roleDao.insert(role);
            //2.中间表
            //如何获得新增数据的id
            middleDao.insertMiddle(k,ids);
            i = 1;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        return i;
    }

    @Override
    public Role findById(int rid) {
        return roleDao.findById(rid);
    }

    @Override
    public int updateRole(int rid, String roleName, String state, String[] ids) {
        int key = 0;
        try {
            Role role = new Role();
            role.setRoleId(rid);
            role.setRoleName(roleName);
            role.setRoleState(Integer.parseInt(state));
            int update = roleDao.update(role);//修改role表的数据
            int i = middleDao.deleteMid(rid);//删除原来的角色所对应的菜单列表
            middleDao.insertMiddle(rid,ids);
            key = 1;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        return key;
    }

    @Override
    public int delete(int rid) {
        int del = 0;
        try {
            int i = middleDao.deleteMid(rid);
            int delete = roleDao.delete(rid);
            del = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return del;
    }

    @Override
    public int start(int rid) {
        return roleDao.start(rid);
    }
}
